import React from 'react';
import { Layout, Menu } from 'antd';
import {
  DashboardOutlined,
  BugOutlined,
  BookOutlined,
  FolderOutlined,
  BarChartOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { useHistory, useLocation } from 'react-router-dom';
import { useUser } from '../contexts/UserContext';

const { Sider } = Layout;

const Sidebar = () => {
  const history = useHistory();
  const location = useLocation();
  const { user, hasPermission } = useUser();

  // 基础菜单项目（包含权限检查）
  const allMenuItems = [
    {
      key: '/',
      icon: <DashboardOutlined />,
      label: '仪表板',
      permission: 'view_dashboard'
    },
    {
      key: '/issues',
      icon: <BugOutlined />,
      label: '问题管理',
      permission: 'manage_issues'
    },
    {
      key: '/cases',
      icon: <BookOutlined />,
      label: '案例库',
      permission: 'manage_cases'
    },
    {
      key: '/resources',
      icon: <FolderOutlined />,
      label: '资源中心',
      permission: 'manage_resources'
    },
    {
      key: '/reports',
      icon: <BarChartOutlined />,
      label: '统计报表',
      permission: 'view_reports'
    },
    {
      key: '/settings',
      icon: <SettingOutlined />,
      label: '系统设置',
      permission: 'system_settings'
    }
  ];

  // 根据用户角色过滤菜单项
  const menuItems = allMenuItems.filter(item => {
    if (!user || !item.permission) return true; // 无权限要求的项目总是显示
    return hasPermission(item.permission);
  });

  const handleClick = ({ key }) => {
    history.push(key);
  };

  // 根据当前路径确定选中的菜单项
  const getSelectedKey = () => {
    const path = location.pathname;
    if (path.startsWith('/issues')) return '/issues';
    if (path.startsWith('/cases')) return '/cases';
    if (path.startsWith('/resources')) return '/resources';
    if (path.startsWith('/reports')) return '/reports';
    if (path.startsWith('/settings')) return '/settings';
    return '/';
  };

  return (
    <Sider
      breakpoint="lg"
      collapsedWidth="0"
      onBreakpoint={(broken) => {
        console.log(broken);
      }}
      onCollapse={(collapsed, type) => {
        console.log(collapsed, type);
      }}
    >
      <div className="logo" style={{ 
        height: '32px', 
        margin: '16px', 
        background: 'rgba(255, 255, 255, 0.3)',
        color: 'white',
        textAlign: 'center',
        lineHeight: '32px'
      }}>
        ITS
      </div>
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={[getSelectedKey()]}
        items={menuItems}
        onClick={handleClick}
      />
    </Sider>
  );
};

export default Sidebar;